<template>
  <view class="scroll-wrap">
    <slot></slot>
    <view class="tag" v-if="more"></view>
  </view>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, onUnmounted, watchEffect } from "vue";

const props: any = defineProps({
  more: { type: Boolean, default: false },
  finished: { type: Boolean, default: false },
  loading: { type: Boolean, default: true },
});

const emit: any = defineEmits(["load", "refresh"]);

//  获取组件实例
const instance: any = getCurrentInstance();

const observer = ref(null) as any;

watchEffect(() => {
  console.log(props.loading);
  if (props.loading) {
    showLoading();
  } else {
    hideLoading();
  }
});

//  页面下拉刷新
onPullDownRefresh(() => {
  console.log("触发了下拉刷新");

  //  会传入一个回调函数， 用于关闭下拉刷新
  emit("refresh", () => {
    uni.stopPullDownRefresh(); // 停止下拉刷新动画
  });
});

onMounted(() => {
  bindEvent();
});

//  销毁的时候移除监听
onUnmounted(() => {
  if (observer.value) {
    cancelObserve();
  }
});

//  绑定元素 - 用于加载更多
function bindEvent() {
  if (props.more) {
    observer.value = uni.createIntersectionObserver(instance, {
      thresholds: [0.5], // 相交比例阈值
      observeAll: false, // 是否同时观测多个目标节点
      nativeMode: false, // 是否使用原生模式
    } as any);

    //   指定相对应的元素
    observer.value.relativeTo(".scroll-wrap");
    //   observer.value.relativeToViewport({ bottom: 0 }) // 设置页面显示区域作为参考区域，底部扩展 100px

    //  监听是否到达该位置
    observer.value.observe(".tag", (res: any) => {
      //  如果到底部了，就让他停掉
      if (props.finished) return;

      //  触碰比例
      const { intersectionRatio } = res;

      console.log(props.finished);
      //  >= .5  说明是上拉加载更多, 第一次会默认执行
      if (intersectionRatio >= 0.5 && !props.finished) {
        console.log("上拉加载更多");
        emit("load");
      }
    });
  } else {
    emit("load");
  }
}

function showLoading() {
  uni.showLoading({
    title: "数据加载中",
  });
}

function hideLoading() {
  uni.hideLoading();
}

function cancelObserve() {
  if(observer.value) {
    observer.value.disconnect();
    observer.value = null;
  }
}
</script>

<style lang="scss" scoped>
.scroll-wrap {
  flex: 1;
  width: 100%;
  overflow-y: auto;

  /* 去掉小程序 scroll-view 组件的滚动条 */
  scrollbar-width: none !important; /* Firefox */
  -ms-overflow-style: none !important; /* IE/Edge */

  &::-webkit-scrollbar {
    display: none !important; /* Chrome, Safari, Opera */
  }

  .tag {
    height: 100rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background: yellowgreen;

    .image-box {
      width: 60rpx;
      height: 60rpx;
    }
  }
}
</style>
